//
//  LoginningVC.m
//  Cunli
//
//  Created by ZhanyaaLi on 15/11/10.
//  Copyright © 2015年 lilubin. All rights reserved.
//

#import "LoginningVC.h"
#import "UIImageView+WebCache.h"
#import "MyDataService.h"
#import "User.h"
#import "CompleteDataTableVC.h"
#import "LoginVC_new.h"
#import "MainTabbarVC.h"
#import "Config.h"
#import "NSString+MD5.h"
#import "MMDrawerController.h"
#import "SidePersonMenuVC.h"
#import "EaseMobHeaders.h"

#define KCLPORTRAITCHANGE @"portraitChanged"
#define KNOTIFICATIONJUMP @"notificationjump"

@interface LoginningVC ()

@end

@implementation LoginningVC
/*
- (instancetype)init
{
    if (self = [super init]) {
        
    }
    return self;
}
*/
- (instancetype)initWithLaunchOptions:(NSDictionary *)launchOptions
{
    if (self = [super init]) {
        _launchOptions = launchOptions;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    __weak __typeof(self) weakSelf = self;
    // Do any additional setup after loading the view.
    UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    bgImgView.tag = 1000;
    NSLog(@"In LOGINNING :%@", NSStringFromCGRect(bgImgView.frame));
//    bgImgView.contentMode = UIViewContentModeScaleToFill;
    UIImage *bgImage = [UIImage imageNamed:@"Default-568"];
    [bgImgView setImage:bgImage];
    [self.view addSubview:bgImgView];
    
    [self doAutoLogin];
    
    [MyDataService requestURL:@"app_start_banner.php" httpMethod:@"GET" params:nil fileDatas:nil complection:^(id result) {
        NSLog(@"APPSTART RESULT:%@", result);
        if ([result[@"response"] isEqualToString:@"app_start_banner"]) {
            NSDictionary *dataDic = result[@"data"];
            NSString *imageUrl = dataDic[@"pic"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [bgImgView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"Default-568"]];
            });
        }
    } failureAction:^{
   
    }];
    
}

//- (void)loginStateChange:(NSNotification *)notification
- (void)doAutoLogin
{
    if([Config isAutoLogin])
    {
        if ([Config getUserPwd] != nil && [Config getOwnUsername] != nil)
        {
            [self reloadUserInfo];
        }
        else
        {
            LoginVC_new *loginVC = [[LoginVC_new alloc] init];
            loginVC.netCheck = @"";
            [self performSelector:@selector(setRootViewControllerAfter2Seconds:) withObject:loginVC afterDelay:2.0f];
        }
        
    }
    else //登录失败加载登录控制器
    {
//      _mainController = nil;
        LoginVC_new *loginVC = [[LoginVC_new alloc] init];
        loginVC.netCheck = @"";
        [self performSelector:@selector(setRootViewControllerAfter2Seconds:) withObject:loginVC afterDelay:2.0f];
    }
}

- (void)reloadUserInfo
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:3];
    [params setObject:[Config getOwnUsername] forKey:@"username"];
    [params setObject:[Config getUserPwd] forKey:@"password"];
    [params setObject:@"1" forKey:@"appkey"];
    [params setObject:@"1" forKey:@"os"];
    [params setObject:@"1" forKey:@"udid"];
    [params setObject:@"1" forKey:@"osversion"];
    [params setObject:@"1" forKey:@"appversion"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    
    //NSLog(@"Login params:%@", params);
    [MyDataService requestURL:@"login.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
        
        NSLog(@"Login success:%@", result);
        if([[result objectForKey:@"response"] isEqualToString:@"login"])
        {
            [Login doLogin:result[@"userinfo"]];
            [Config saveUserID:[Login curLoginBaseUser].userid];
            if ([[Login curLoginBaseUser].completed isEqualToString:@"Y"]) {
                [self getUserDetailData];
                [self pushToMainVC];
            }
            else
            {
                /*
                NSDictionary *myInvitDic = [Login curLoginBaseUser].invit;
                CompleteDataTableVC *completeVC = [[CompleteDataTableVC alloc] init];
                completeVC.access_token = [Login curLoginBaseUser].usersession;
                completeVC.haveLogin = @"yes";
                completeVC.is_invint = myInvitDic[@"is_invint"];
                [self performSelector:@selector(setRootViewControllerAfter2Seconds:) withObject:completeVC afterDelay:2.0f];
//                [kkWindow setRootViewController:completeVC];
                 */
                LoginVC_new *loginVC = [[LoginVC_new alloc] init];
                loginVC.netCheck = @"";
                [self performSelector:@selector(setRootViewControllerAfter2Seconds:) withObject:loginVC afterDelay:2.0f];
            }
        }
        else
        {
        }
    } failureAction:^{
        LoginVC_new *loginVC = [[LoginVC_new alloc] init];
        loginVC.netCheck = @"error";
        [self performSelector:@selector(setRootViewControllerAfter2Seconds:) withObject:loginVC afterDelay:2.0f];
    }];
}

- (void)pushToMainVC
{
    MainTabbarVC *mainController = [[MainTabbarVC alloc] init];
    SidePersonMenuVC *sideMenuVC = [[SidePersonMenuVC alloc] init];
    MMDrawerController *drawerController = [[MMDrawerController alloc] initWithCenterViewController:mainController leftDrawerViewController:sideMenuVC];
    [drawerController setMaximumLeftDrawerWidth:LEFTSIDEWIDTH];
    //[drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    [self performSelector:@selector(setRootViewControllerAfter2Seconds:) withObject:drawerController afterDelay:2.0f];
}

-(void)loginOnEaseMob{
    
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:[Login curLoginBaseUser].huanxin_username password:[Login curLoginBaseUser].huanxin_password completion:^(NSDictionary *loginInfo, EMError *error) {
        if (!error && loginInfo) {
            NSLog(@">>>>>>>>>>>>>>>登陆成功<<<<<<<<<<<<<<<");
        }
    } onQueue:nil];
}

-(void)getUserDetailData{
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc] init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"getinfo_member.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"getinfo_member in appdelegate:%@",result);
        [Login saveUserDetailData:result[@"userinfo"]];
        [[NSNotificationCenter defaultCenter] postNotificationName:KCLPORTRAITCHANGE object:@YES];
    }failureAction:^{
        
    }];
    
    [self loginOnEaseMob];
}

- (void)setRootViewControllerAfter2Seconds:(UIViewController *)viewController
{
//    UIImageView *bgImageView = (UIImageView *)[self.view viewWithTag:1000];
//    viewController.view.alpha = 0.0f;
    
    [kkWindow setRootViewController:viewController];
    [kkWindow makeKeyAndVisible];
    
    
    if ((_launchOptions != nil) && ([viewController isKindOfClass:[MMDrawerController class]]) ) {
        [self performSelector:@selector(postNotificationZhanyaa:) withObject:_launchOptions afterDelay:1.0f];
    }
    
//    NSLog(@"VC kind:%@", NSStringFromClass([viewController class]));
    /*
    if ([viewController isKindOfClass:[MMDrawerController class]]) {
        NSLog(@">>>mmdrawercontroller>>>");
    }
    */
    /*
    [UIView animateWithDuration:0.6 delay:0.3 options:UIViewAnimationOptionCurveEaseIn animations:^{
//        viewController.view.alpha = 1.0f;
        bgImageView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [bgImageView removeFromSuperview];
    }];
     */
}

- (void)postNotificationZhanyaa:(NSDictionary *)userInfo
{
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATIONJUMP object:userInfo];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

@end
